﻿using UnityEngine;
using QFramework;

#if NET_4_6
using Microsoft.Win32;

public interface IHK_AutoRunSystem : ISystem
{
    void SetupAutoRun();
    void CancelAutoRun();
}

public class HK_AutoRunSystem : AbstractSystem, IHK_AutoRunSystem
{
    string fileName;
    string targetPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
    string productName = "MyProject";

    protected override void OnInit()
    {
#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
        fileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
        productName = Application.productName;
#endif
    }

    public void SetupAutoRun()
    {
#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
        try
        {
            RegistryKey runKey = GetRegistryKey(targetPath);

            if (runKey.GetValue(productName) != null)
            {
                Debug.LogWarning("当前程序已注册过！");
                return;
            }

            runKey.SetValue(productName, fileName);

            Debug.Log("当前程序 已设置为 自动启动！");
        }
        catch
        {
            Debug.LogError(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + " 注册失败!");
        }
#endif
    }

    public void CancelAutoRun()
    {
#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
        try
        {
            RegistryKey runKey = GetRegistryKey(targetPath);
            runKey.DeleteValue(productName, false);

            Debug.Log("当前程序 已取消 自动启动！");

        }
        catch
        {
            Debug.LogError("Error!");
        }
#endif
    }

    RegistryKey GetRegistryKey(string targetPath)
    {
        RegistryKey runKey = Registry.LocalMachine.OpenSubKey(targetPath, true);

        if (runKey == null)
        {
            runKey = Registry.LocalMachine.CreateSubKey(targetPath);
        }

        return runKey;
    }
}
#endif